package com.bookmanger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmanger.common.result.Result;
import com.bookmanger.common.utils.PasswordUtil;
import com.bookmanger.entity.Manager;
import com.bookmanger.entity.User;
import com.bookmanger.entity.dto.LoginDTO;
import com.bookmanger.entity.dto.ManagerDTO;
import com.bookmanger.mapper.UserMapper;
import com.bookmanger.service.LoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.bookmanger.common.utils.RedisConstants.*;

/**
 * @author huangfuhao
 * @Date 2024/11/4
 */
@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<LoginDTO> register(User user) {
        log.info("{}",user);

        //检查用户名是否存在，如果存在则提示用户名已存在
        User one = lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (one != null){
            return Result.error("用户名已存在");
        }

        user.setPassword(PasswordUtil.encodePassword(user.getPassword()));//md5加密
        save(user);
        LoginDTO loginDTO = BeanUtil.copyProperties(user, LoginDTO.class);
        return Result.success(loginDTO);
    }

    @Override
    public Result<LoginDTO> login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();

        //1.查找用户是否存在
        User one = lambdaQuery().eq(User::getUsername, username).one();
        if (one == null) {
            return Result.error("用户不存在");
        }

        //2.存在，判断密码是否正确
        String password1 = one.getPassword();

        if (!PasswordUtil.encodePassword(password).equals(password1)) {
            return Result.error("用户名或密码错误");
        }

        //3.保存用户信息到redis
        //3.1随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //  3.2将User对象转为HashMap存储
        LoginDTO loginDTO = BeanUtil.copyProperties(one, LoginDTO.class);
//        Map<String, Object> loginMap = BeanUtil.beanToMap(loginDTO, new HashMap<>(),
//                CopyOptions.create()
//                        .setIgnoreNullValue(true)
//                        .setFieldValueEditor((fieldName, fieldValue) -> {
//                                    if (fieldValue == null){
//                                        fieldValue = "0";
//                                    }else {
//                                        fieldValue = fieldValue + "";
//                                    }
//                                    return fieldValue;
//                                }));
        //  3.3存储
        String tokenKey = LOGIN_USER_KEY + token;
//        stringRedisTemplate.opsForHash().putAll(tokenKey, loginMap);
        //新的存储方式：存储用户id+权限
        stringRedisTemplate.opsForValue().set(tokenKey,one.getId()+"_user");
        //  3.4设置token有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        //  4.设置token
        loginDTO.setToken(token);
        return Result.success(loginDTO);
    }
}
